package com.cwj.课程设计;

import com.cwj.lab1.myArrayList;

import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.*;
import java.util.Vector;

public class PrepareTable {
    //表格的列的属性设置
    public static final int NUM = 5;
    public static final String[] COLNAME = {"起点", "终点","距离", "时间", "花费" };
    public static final String BufferPath="./src/com/cwj/课程设计/data/lastGraph.txt";//存放上一次用完的数据

    private boolean isBufferSave=false;
    public boolean isModify=true;
//上中下三个页面
    private JPanel mainPanel;
    private JPanel northPanel;
    private JPanel southPanel;

    //文件选择器
    private JFileChooser fileChooser;
    //图名
    private JTextField textGraphName;
    //保存按钮
    private JButton saveGrBut;
    //修改按钮
    private JButton changeNameBut;
//    浏览按钮
    private JButton openBut;

//    private JButton doneBut;
//    新图按钮
    private JButton newGraBut;
//    图表
    private JTable table;
    private DefaultTableModel model;
    private JTextField textField;//文件路径
//    新图的初始化名字
    private final String nullFile = "未选择文件";
//    操作图表下拉框
    private JComboBox<String> cmb;
    //卡片布局
    private CardLayout cardLayout = new CardLayout(5, 5);
    private JPanel southCardPanel;
    private final String c0Name = "新增";
    private final String c1Name = "修改";
    private String cardChoose = this.c0Name;
    //选中显示
    JTextField c2Text;
    //图
    private Graph_Name_star graph;

    //    private
    public PrepareTable() {
        this.prePanel();
        this.preNorthComponent();
        this.preCenterComponent();
        this.preSouth();
    }
//页面初始化
    public void prePanel() {
        mainPanel = new JPanel(new BorderLayout(5, 5));
        northPanel = new JPanel(new FlowLayout(5));
        this.southPanel = new JPanel(new FlowLayout(5));
        this.southCardPanel = new JPanel(this.cardLayout);
        this.southPanel = new JPanel(new FlowLayout(5));
        mainPanel.add(northPanel, BorderLayout.NORTH);
        mainPanel.add(southPanel, BorderLayout.SOUTH);
    }
//BorderLayout.NORTH部分的初始化
    public void preNorthComponent() {
        JLabel label = new JLabel("路径：");
        JLabel graphName=new JLabel("图名");
        fileChooser = new JFileChooser(".\\");
        openBut = new JButton("浏览");
//        doneBut = new JButton("导入");
        newGraBut=new JButton("新表");
        this.changeNameBut=new JButton("修改");
        this.saveGrBut=new JButton("导出");
        this.textGraphName=new JTextField(8);
        this.textField = new JTextField(25);
//打开文件
        openBut.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                openFile();
                initGraph();
//                bufferSave();
            }
        });
//        导出按钮
        this.saveGrBut.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //导出为文件
                JFileChooser fileChooser1=new JFileChooser(".\\");
                int val=fileChooser1.showSaveDialog(saveGrBut);
                if(val==JFileChooser.APPROVE_OPTION){
                    File file=fileChooser1.getSelectedFile();
                    //saveGraph(file);
                    Graph_Name_star gg=toGraph();
                    if(gg==null)return;
                    gg.saveGraph(file.toString());
                }else{
                    JOptionPane.showMessageDialog(saveGrBut,"导出失败","提示",JOptionPane.INFORMATION_MESSAGE);
                }
            }
        });
        this.changeNameBut.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //修改图名
                String str=null;
                if(!(str=graphName.getText()).equals("")&&graph!=null){
                    graph.setGraphName(str);
                }
            }
        });
        this.newGraBut.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                newGraph();
            }
        });
        northPanel.add(label);
        northPanel.add(textField);
        northPanel.add(this.openBut);
        northPanel.add(this.newGraBut);
        northPanel.add(graphName);
        northPanel.add(this.textGraphName);
        northPanel.add(changeNameBut);
        northPanel.add(this.saveGrBut);
        //northPanel.add(this.doneBut);
    }

    /**
     * 导入通过路径建图
     */
    private void initGraph() {
        String str = textField.getText();
        if (!str.equals("") && !str.equals(nullFile)) {
            try {
                graph = new Graph_Name_star(str);
                printGraphTable();
                textGraphName.setText(this.graph.getGraphName());
                table.repaint();
            } catch (FileNotFoundException fileNotFoundException) {
                JOptionPane.showMessageDialog(null, "未找到文件", "提示", JOptionPane.INFORMATION_MESSAGE);
                //fileNotFoundException.printStackTrace();
            }
        }
    }
    /**
     * 导出图，有表导出图
     * */
    public void saveGraph(File file) throws IOException {
        int Len=this.table.getRowCount();
        try(BufferedWriter out=new BufferedWriter(new FileWriter(file))){
            out.write(Graph_Name_star.DIRECTNAME);
            out.newLine();
            out.write(this.graph.getGraphName());
            out.newLine();
            out.write(this.graph.getV_num()+"\t");
            out.write(this.graph.getE_num()+"");
            out.newLine();
            for (int i = 0; i < Len; i++) {
                for (int j = 0; j < PrepareTable.NUM; j++) {
                    out.write(this.table.getValueAt(i,j).toString()+"\t");
                }
                out.newLine();
            }
        }

    }
//    BorderLayout.CENTER部分的初始化
    void preCenterComponent() {

        model = new DefaultTableModel(PrepareTable.COLNAME, PrepareTable.COLNAME.length);
        model.setRowCount(0);
        table = new JTable(model);
//        table.setEnabled(false);
        //用于删除界面的选择显示
        table.addMouseListener(new MouseListener() {
            @Override
            public void mouseClicked(MouseEvent e) {
                int ind = table.getSelectedRow();
                if (ind == -1) {
                    return;
                }
                Object oo = null;
                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < NUM; i++) {
                    if (ind >= table.getRowCount()) {
                        return;
                    }
                    if ((oo = model.getValueAt(ind, i)) == null) {
                        continue;
                    }
                    sb.append(oo.toString()).append(" ");
                }
                c2Text.setText(sb.toString());
//                table.repaint();
            }

            @Override
            public void mousePressed(MouseEvent e) {
            }

            @Override
            public void mouseReleased(MouseEvent e) {
            }

            @Override
            public void mouseEntered(MouseEvent e) {
            }

            @Override
            public void mouseExited(MouseEvent e) {
            }
        });
        this.model.addTableModelListener(new TableModelListener() {
            @Override
            public void tableChanged(TableModelEvent e) {
                isModify=true;
            }
        });
        this.bufferRead();
        JScrollPane scrollPane = new JScrollPane(table);
        this.mainPanel.add(scrollPane, BorderLayout.CENTER);
    }
//BorderLayout.SOUTH部分的初始化
    public void preSouth() {
        this.cmb = new JComboBox<>();
        cmb.addItem("新增路线");
        cmb.addItem("修改路线");
//        cmb.addItem("删除路线");
//        选择卡片
        this.cmb.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int val = cmb.getSelectedIndex();
                switch (val) {
                    case 0:
                        cardChoose = c0Name;
                        break;
                    case 1:
                        cardChoose = c1Name;
                        break;
                }
                cardLayout.show(southCardPanel, cardChoose);
            }
        });
        this.southPanel.add(cmb, BorderLayout.SOUTH);
        this.preSouthCard();
    }
//卡片布局初始化
    public void preSouthCard() {
        this.southPanel.add(this.southCardPanel);
        //新增
        JPanel card1 = new JPanel(new FlowLayout(5));
        int TextSize = 4;
        JLabel c1Label = new JLabel("起点");
        JTextField c1Text1 = new JTextField(TextSize);
        JLabel c1Label2 = new JLabel("终点");
        JTextField c1Text2 = new JTextField(TextSize);
        JButton c1But = new JButton("添加");
        JLabel c1TimeLabel = new JLabel("时间：");
        JTextField c1TimeText = new JTextField(TextSize);
        JLabel c1DisLabel = new JLabel("距离：");
        JTextField c1DisText = new JTextField(TextSize);
        JLabel c1MoneyLabel = new JLabel("开销：");
        JTextField c1MoneyText = new JTextField(TextSize);
        myArrayList<JTextField> textList = new myArrayList<>();
        textList.addLast(c1Text1);
        textList.addLast(c1Text2);
        textList.addLast(c1DisText);
        textList.addLast(c1TimeText);
        textList.addLast(c1MoneyText);
        c1But.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String str = null;
                Vector<String> list = new Vector<>();
                for (int i = 0; i < textList.size(); i++) {
                    if ((str = textList.get(i).getText()).equals("")) {
                        JOptionPane.showMessageDialog(c1But, "信息不能为空！", "错误", 0);
                        return;
                    } else {
                        list.add(str);
                        //graph.setE_num(graph.getE_num()+1);
                    }
                }
                //String[]strList={c1Text1.getText().toString(),c1Text2.toString(),c1TimeText.toString(),c1MoneyText.toString(),c1DisText.toString()};
                model.addRow(list);
                table.repaint();
                c1Text1.setText("");
                c1Text2.setText("");
                c1DisText.setText("");
                c1MoneyText.setText("");
                c1TimeText.setText("");
            }
        });

        card1.add(c1Label);
        card1.add(c1Text1);
        card1.add(c1Label2);
        card1.add(c1Text2);
        card1.add(c1DisLabel);
        card1.add(c1DisText);
        card1.add(c1TimeLabel);
        card1.add(c1TimeText);
        card1.add(c1MoneyLabel);
        card1.add(c1MoneyText);
        card1.add(c1But);

        //修改
        JPanel card2 = new JPanel(new FlowLayout(5));
//        JLabel c2Label=new JLabel("起点");
//        JLabel c2Label2=new JLabel("终点");
        JLabel c2DelLabel = new JLabel("请选择上面表格的行");
        c2Text = new JTextField(11);
        JButton c2DelBut = new JButton("删除");
        c2Text.setEditable(false);

        c2DelBut.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                int[] nums = table.getSelectedRows();
                if (nums.length == 0) {
                    JOptionPane.showMessageDialog(c2DelBut, "没有选择行！", "错误", 0);
                } else {
                    for (int i = nums.length - 1; i >= 0; i -= 1) {
                        model.removeRow(nums[i]);
                        graph.setE_num(graph.getE_num()-1);
                    }
                }
                table.repaint();
            }
        });
//        JButton c2DoneBut=new JButton("修改");
//        JComboBox<String>c2cmb1=new JComboBox<>();
//        JComboBox<String>c2cmb2=new JComboBox<>();
//        card2.add(c2Label);
//        card2.add(c2cmb1);
//        card2.add(c2Label2);
//        card2.add(c2cmb2);
//        card2.add(c2DoneBut);
        card2.add(c2DelLabel);
        card2.add(c2Text);
        card2.add(c2DelBut);

        //加入面板
        this.southCardPanel.add(card1, this.c0Name);
        this.southCardPanel.add(card2, this.c1Name);
        CardLayout cardPanel = (CardLayout) this.southCardPanel.getLayout();
        cardPanel.show(this.southCardPanel, this.cardChoose);
    }

    private void openFile() {
        int val = this.fileChooser.showOpenDialog(null);
        if (val == JFileChooser.APPROVE_OPTION) {
            textField.setText(this.fileChooser.getSelectedFile().toString());
        } else {
            textField.setText(this.nullFile);
        }
    }

    public JPanel getMainPanel() {
        return mainPanel;
    }

    /**
     * 以图填表
     */
    public void printGraphTable() {
        int Len = 0;
        myArrayList<Graph_Name_star.Edge> list = null;
        Graph_Name_star.Edge ee = null;
        String[][] tableData = new String[this.graph.getE_num()][PrepareTable.NUM];
        String name = null;
        Graph_Name_star.Data data = null;
        int cnt = 0;
        for (int i = 0; i < this.graph.getV_num(); i++) {
            name = this.graph.getNodeName(i);
            list = this.graph.getNode_Edge(i);
            for (int j = 0; j < list.size(); j++) {
                ee = list.get(j);
                data = this.graph.getData(ee.indVal);
                tableData[cnt][0] = name;
                tableData[cnt][1] = this.graph.getNodeName(ee.v);
                tableData[cnt][2] = data.dis + "";
                tableData[cnt][3] = data.time + "";
                tableData[cnt][4] = data.money + "";
                cnt += 1;
            }
        }
        this.model.setDataVector(tableData, PrepareTable.COLNAME);
    }
    /**
     * 将表转换为图*/
    public Graph_Name_star toGraph(){
        if(table.getRowCount()==0){
            return null;
        }
        Graph_Name_star gg=new Graph_Name_star(this.table,this.textGraphName.getText());
//        gg.show();
        return gg;
    }
    //缓存写入
    public void bufferRead(){
        this.textField.setText(PrepareTable.BufferPath);
        initGraph();
    }
    /**
     * 其在导出的时候，以及选项切换的时候，但仅仅会写入一次，为了提高效率
     * */
    public void bufferSave(){
        if(isBufferSave){
            return ;
        }
        isBufferSave=true;
        Graph_Name_star gg=this.toGraph();
        if(gg!=null){
            gg.saveGraph(PrepareTable.BufferPath);
        }
    }
    //建图按钮
    private void newGraph(){
        this.model.setRowCount(0);
        this.textGraphName.setText("未命名");
    }

    public void setModify(boolean modify) {
        isModify = modify;
    }

    public boolean isModify() {
        return isModify;
    }

    public static void main(String[] args) {
        JFrame jFrame = new JFrame();
        jFrame.setContentPane(new PrepareTable().mainPanel);
        jFrame.pack();//setSize(500,600);
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jFrame.setVisible(true);
    }
}
